# -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp import netsvc
from openerp.tools.float_utils import float_compare
#----------------------------------------------------------
# Purchase Order
#----------------------------------------------------------

class purchase_order(osv.osv):

    _inherit = "purchase.order"
    
    def po_print2(self, cr, uid, ids, context=None):
        if context is None:
           context = {}
        data = self.read(cr, uid, ids)[0]
        self_browse = self.browse(cr, uid, ids)
        
        datas = {
            'ids': [data.get('id')],
            'model': 'purchase.order',
            'form': data
            }
        return {
            'type': 'ir.actions.report.xml',
            'report_name': 'batam_fast_module.report_invoice2',
            'datas': datas,
            'name': self_browse.name
            }
    
    def onchange_ceo_id(self, cr, uid, ids, ceo_id, context=None):
        group_obj = self.pool.get('res.groups')
        if context is None:
            context = {}
        res = {}
        res_groups = group_obj.search(cr, uid, [('name', 'in', ('CEO Default',))], context=context)

        cr.execute('''SELECT S.id as id
                FROM res_users S
                WHERE EXISTS (SELECT 1 FROM res_groups_users_rel G WHERE G.gid in %s)
                        AND active = True
                ORDER BY S.id LIMIT 1
        ''', (tuple(res_groups),))
        data_user = cr.dictfetchone()
        if not data_user:
            res_groups2 = group_obj.search(cr, uid, [('name', '=', 'CEO')], context=context)[0]
            cr.execute('''SELECT S.id as id
                FROM res_users S
                WHERE EXISTS (SELECT 1 FROM res_groups_users_rel G WHERE G.gid = %s)
                        AND active = True
                ORDER BY S.id LIMIT 1
                ''', (res_groups2,))
            data_user = cr.dictfetchone()

        if not data_user:
            raise osv.except_osv(_('Error!'), _("Make sure you have at least a CEO user defined"))
        res_groups3 = group_obj.search(cr, uid, [('name', '=', 'CEO')], context=context)[0]
        cr.execute('''SELECT S.id as id
            FROM res_users S
            WHERE S.id in (SELECT uid FROM res_groups_users_rel G WHERE G.gid = %s)
                    AND active = True
            ORDER BY S.id
            ''', (res_groups3,))
        user_ids = cr.dictfetchall()
        found = False
        ceo_ids = []
        for r in user_ids:
            ceo_ids.append(r['id'])
            if ceo_id == r['id']:
                found = True
        res['domain'] = {'ceo_id': [('id','in',tuple(ceo_ids))]}
        if not found:
            res['warning'] = {'title': _('Warning!'), 'message': _('The Selected CEO User is not at CEO position.')}
#             ceo_id = data_user['id']
            res['value'] = {'ceo_id': False}
#         raise osv.except_osv(_('Error!'), _("Make sure you have at least a CEO user defined"))
        return res
    
    def onchange_financial_id(self, cr, uid, ids, ceo_id, context=None):
        group_obj = self.pool.get('res.groups')
        if context is None:
            context = {}
        res = {}
        res_groups = group_obj.search(cr, uid, [('name', 'in', ('Financial Manager PO Default',))], context=context)

        cr.execute('''SELECT S.id as id
                FROM res_users S
                WHERE EXISTS (SELECT 1 FROM res_groups_users_rel G WHERE G.gid in %s)
                        AND active = True
                ORDER BY S.id LIMIT 1
        ''', (tuple(res_groups),))
        data_user = cr.dictfetchone()
        if not data_user:
            res_groups2 = group_obj.search(cr, uid, [('name', '=', 'Financial Manager PO')], context=context)[0]
            cr.execute('''SELECT S.id as id
                FROM res_users S
                WHERE EXISTS (SELECT 1 FROM res_groups_users_rel G WHERE G.gid = %s)
                        AND active = True
                ORDER BY S.id LIMIT 1
                ''', (res_groups2,))
            data_user = cr.dictfetchone()

        if not data_user:
            raise osv.except_osv(_('Error!'), _("Make sure you have at least a CEO user defined"))
        res_groups3 = group_obj.search(cr, uid, [('name', '=', 'Financial Manager PO')], context=context)[0]
        cr.execute('''SELECT S.id as id
            FROM res_users S
            WHERE S.id in (SELECT uid FROM res_groups_users_rel G WHERE G.gid = %s)
                    AND active = True
            ORDER BY S.id
            ''', (res_groups3,))
        user_ids = cr.dictfetchall()
        found = False
        ceo_ids = []
        for r in user_ids:
            ceo_ids.append(r['id'])
            if ceo_id == r['id']:
                found = True
        res['domain'] = {'financial_manager_id': [('id','in',tuple(ceo_ids))]}
        if not found:
            res['warning'] = {'title': _('Warning!'), 'message': _('The Selected Financial Manager User is not at Financial Manager position.')}
#             ceo_id = data_user['id']
            res['value'] = {'financial_manager_id': False}
#         raise osv.except_osv(_('Error!'), _("Make sure you have at least a CEO user defined"))
        return res

    def wkf_confirm_order(self, cr, uid, ids, context=None):
        todo = []
        for po in self.browse(cr, uid, ids, context=context):
            if not po.order_line:
                raise osv.except_osv(_('Error!'),_('You cannot confirm a purchase order without any purchase order line.'))
            for line in po.order_line:
                if line.state=='draft':
                    todo.append(line.id)     
            if po.pricelist_id.currency_id.name == "SGD":
                
                if po.amount_total > 5000:
                    self.message_post(cr, uid, ids, body=_('Purchase Order %s has been confirmed by supervisor.') % (po.name,),
                        partner_ids=[po.ceo_id.partner_id.id],
                        context=context)  
                else:
                    self.message_post(cr, uid, ids, body=_('Purchase Order %s has been confirmed by supervisor.') % (po.name,),
                        partner_ids=[po.financial_manager_id.partner_id.id],
                        context=context)
            else:
                self.message_post(cr, uid, ids, body=_('Purchase Order %s has been confirmed by supervisor.') % (po.name,),
                        partner_ids=[po.financial_manager_id.partner_id.id],
                        context=context)

        self.pool.get('purchase.order.line').action_confirm(cr, uid, todo, context)
        for id in ids:
            self.write(cr, uid, [id], {'state' : 'confirmed', 'validator' : uid})
        return True

    def wkf_approve_order(self, cr, uid, ids, context=None):
        for po in self.browse(cr, uid, ids, context=context):
            self.message_post(cr, uid, ids, body=_('Purchase Order %s has been approved.') % (po.name,),
                    partner_ids=[po.create_uid.partner_id.id],
                    context=context)
            
        self.write(cr, uid, ids, {'state': 'approved', 'date_approve': fields.date.context_today(self,cr,uid,context=context)})
        return True
    
    def test_message_ceo(self, cr, uid, ids, context=None):
        for st in self.browse(cr, uid, ids, context=context):
            if st.send_po == True:
                self.write(cr, uid, ids, {'send_po': False})
            elif st.send_po == False:
                self.write(cr, uid, ids, {'send_po': True})
        return True


    def _get_ceo(self, cr, uid, context=None):
        obj_data = self.pool.get('ir.model.data')
        user_obj = self.pool.get('res.users')
        group_obj = self.pool.get('res.groups')
        company_id = user_obj.browse(cr, uid, uid, context=context).company_id.id
        res_groups = group_obj.search(cr, uid, [('name', 'in', ('CEO Default',))], context=context)
        data_user = False
        if res_groups:
            cr.execute('''SELECT S.id as id
                    FROM res_users S
                    WHERE EXISTS (SELECT 1 FROM res_groups_users_rel G WHERE G.gid in %s and G.uid = S.id)
                            AND active = True
                    ORDER BY S.id LIMIT 1
            ''', (tuple(res_groups),))
            data_user = cr.dictfetchone()
        if not data_user:
            res_groups2 = group_obj.search(cr, uid, [('name', '=', 'CEO')], context=context)
            if res_groups2:
                cr.execute('''SELECT S.id as id
                    FROM res_users S
                    WHERE EXISTS (SELECT 1 FROM res_groups_users_rel G WHERE G.gid = %s and G.uid = S.id)
                            AND active = True
                    ORDER BY S.id LIMIT 1
                    ''', (res_groups2[0],))
                data_user = cr.dictfetchone()
        if not data_user:
            raise osv.except_osv(_('Error!'), _("Make sure you have at least a CEO user defined"))
        return data_user['id']


    def _get_financial(self, cr, uid, context=None):
        obj_data = self.pool.get('ir.model.data')
        user_obj = self.pool.get('res.users')
        group_obj = self.pool.get('res.groups')
        company_id = user_obj.browse(cr, uid, uid, context=context).company_id.id
        res_groups = group_obj.search(cr, uid, [('name', 'in', ('Financial Manager PO Default',))], context=context)
        data_user = False
        if res_groups:
            cr.execute('''SELECT S.id as id
                    FROM res_users S
                    WHERE EXISTS (SELECT 1 FROM res_groups_users_rel G WHERE G.gid in %s and G.uid = S.id)
                            AND active = True
                    ORDER BY S.id LIMIT 1
            ''', (tuple(res_groups),))
            data_user = cr.dictfetchone()
  
        if not data_user:
            res_groups2 = group_obj.search(cr, uid, [('name', '=', 'Financial Manager PO')], context=context)
            if res_groups2:
                cr.execute('''SELECT S.id as id
                    FROM res_users S
                    WHERE EXISTS (SELECT 1 FROM res_groups_users_rel G WHERE G.gid = %s and G.uid = S.id)
                            AND active = True
                    ORDER BY S.id LIMIT 1
                    ''', (res_groups2[0],))
                data_user = cr.dictfetchone()
        if not data_user:
            raise osv.except_osv(_('Error!'), _("Make sure you have at least a Financial Manager PO user defined"))
  
        return data_user['id']

    _columns = {
        'send_po':fields.boolean('Send to Supplier', readonly=True, select=True, copy=False,
                                 help="It indicates that a PO has been sent to supplier"),
        'order_line': fields.one2many('purchase.order.line', 'order_id', 'Order Lines',
                                      states={'confirmed':[('readonly',True)],
                                              'approved':[('readonly',True)],
                                              'done':[('readonly',True)]},
                                      copy=True),
        'ceo_id' : fields.many2one('res.users', 'CEO',
                                   states={'confirmed':[('readonly',True)],
                                              'approved':[('readonly',True)],
                                              'done':[('readonly',True)]},
                                   copy=False),
        'financial_manager_id' : fields.many2one('res.users', 'Financial Manager',
                                   states={'confirmed':[('readonly',True)],
                                              'approved':[('readonly',True)],
                                              'done':[('readonly',True)]},
                                   copy=False),
        'remark' : fields.text('Remark', states={'confirmed':[('readonly',True)],
                                              'approved':[('readonly',True)],
                                              'done':[('readonly',True)]},)
    }


    _defaults = {
        'ceo_id': _get_ceo,
        'financial_manager_id': _get_financial,
    }

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
